package pit.com.ordermobilesystem;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import pit.com.ordermobilesystem.http.Group;
import pit.com.ordermobilesystem.http.HttpApiException;
import pit.com.ordermobilesystem.http.OrderSystemHttpService;
import pit.com.ordermobilesystem.http.Response;
import pit.com.ordermobilesystem.model.Category;
import pit.com.ordermobilesystem.model.Item;
import pit.com.ordermobilesystem.provider.OrderMobileProvider;
import pit.com.ordermobilesystem.tabhost.TabGroup1Activity;
import pit.com.ordermobilesystem.tabhost.TabGroup2Activity;
import pit.com.ordermobilesystem.tabhost.TabGroup3Activity;
import pit.com.ordermobilesystem.tabhost.TabGroup4Activity;
import pit.com.ordermobilesystem.util.OrderConstant;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.widget.TabHost;

@SuppressWarnings({ "deprecation" })
public class MainActivity extends TabActivity implements OrderConstant {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.table_main);
		getContentResolver().delete(OrderMobileProvider.ITEM_CONTENT_URI, null, null);
		getContentResolver().delete(OrderMobileProvider.CATEGORY_CONTENT_URI, null, null);
		new LoadingCategory().execute("");

        TabHost tabHost = getTabHost();       
        
      tabHost.addTab(tabHost.newTabSpec("tab1")
              .setIndicator("", getResources().getDrawable(R.drawable.icon_home))
              .setContent(new Intent(this, TabGroup1Activity.class)));
      
      tabHost.addTab(tabHost.newTabSpec("tab2")
              .setIndicator("",getResources().getDrawable(R.drawable.icon_menu))
              .setContent(new Intent(this, TabGroup2Activity.class)));
      
      tabHost.addTab(tabHost.newTabSpec("tab3")
              .setIndicator("",getResources().getDrawable(R.drawable.icon_payment))
              .setContent(new Intent(this, TabGroup3Activity.class)));
      
      tabHost.addTab(tabHost.newTabSpec("tab4")
              .setIndicator("",getResources().getDrawable(R.drawable.icon_update))
              .setContent(new Intent(this, TabGroup4Activity.class)));
      
      
      tabHost.setCurrentTab(0);

	}

	ContentObserver contentObserver = new ContentObserver(new Handler()) {

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			synchronized (this) {
				Cursor data = getContentResolver().query(
						OrderMobileProvider.CATEGORY_CONTENT_URI, null, null,
						null, null);
				// code here adapters
				data.close();
			}
		}
	};

	@Override
	public void onPause() {
		super.onPause();
		getContentResolver().unregisterContentObserver(contentObserver);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getContentResolver()
				.registerContentObserver(
						OrderMobileProvider.CATEGORY_CONTENT_URI, true,
						contentObserver);
		contentObserver.onChange(false);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	class LoadingCategory extends AsyncTask<String, Void, Void> {

		private Exception exception = null;
		ProgressDialog dialog;
		Response respone;
		Group<Category> list;
		Group<Item> listItems;
		String notice = "Loading Category. Please wait...";

		protected void onPreExecute() {

			dialog = new ProgressDialog(MainActivity.this);
			dialog.setMessage(notice);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					LoadingCategory.this.cancel(true);
					dialog.dismiss();
				}

			});
			dialog.show();

		}

		@Override
		protected void onProgressUpdate(Void... values) {
			dialog.setMessage(notice);
		}

		protected Void doInBackground(final String... args) {
			OrderSystemHttpService httpService = new OrderSystemHttpService(
					SERVER_HOST, PORT);
			try {
				list = httpService.downloadCategoryGroup();
				ContentValues[] listValues = new ContentValues[list.size()];

				for (int i = 0; i < list.size(); i++) {
					listValues[i] = OrderMobileProvider
							.getcontentValuesCategory(list.get(i));
				}
				// Insert into database
				getContentResolver().bulkInsert(
						OrderMobileProvider.CATEGORY_CONTENT_URI, listValues);

				notice = "Loading Items, please waiting ....";
				setProgress(1);

				listItems = httpService.downloadItemGroup();
				ContentValues[] listValuesItems = new ContentValues[listItems
						.size()];

				for (int i = 0; i < listItems.size(); i++) {
					listValuesItems[i] = OrderMobileProvider
							.getContentValuesItem(listItems.get(i));
				}
				// Insert into database
				getContentResolver().bulkInsert(
						OrderMobileProvider.ITEM_CONTENT_URI, listValuesItems);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				exception = e;
			} catch (HttpApiException e) {
				// TODO Auto-generated catch block
				exception = e;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				exception = e;
			}
			return null;
		}

		protected void onPostExecute(final Void unused) {
			dialog.cancel();

			if (exception == null) {
				if (list != null && list.size() != 0) {

				} else {

				}
			} else {

			}

		}

	}

}
